<?php
declare (strict_types=1);

namespace app\admin\controller\tour;

use app\admin\controller\CommonController;
use app\common\model\BaseArea;
use app\common\model\TourRoute;
use app\common\model\TourTemplate;
use think\db\BaseQuery;
use think\facade\Db;

class Route extends CommonController
{
    protected $modelName = TourRoute::MODEL_NAME;
    protected $alias = 'r';

    protected function indexPage($param)
    {
        $param['r_start_ge'] = date('Y-m-d');
        return parent::indexPage($param);
    }

    protected function getSearchFields(): string
    {
        return "{$this->alias}.*,t.code,t.name,t.days,t.pic,province.name destination_name";
    }

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(TourTemplate::MODEL_NAME . ' t', "{$this->alias}.template_id=t.id")
            ->leftJoin(BaseArea::MODEL_NAME . ' destination', "t.destination_id=destination.id")
            ->leftJoin(BaseArea::MODEL_NAME . ' province', "destination.parent_id=province.id");
    }

    protected function getSearchDefaultSort(): array
    {
        return ["{$this->alias}.start" => 'asc'];
    }

    protected function addPage()
    {
        $template = TourTemplate::getById(request()->param('template_id'));
        $this->assign('template', $template);
        return parent::addPage();
    }

    protected function addOperate()
    {
        $data = request()->param();
        if (!empty($data['dates'])) {
            $dates = explode(',', $data['dates']);
        } else {
            $dates = [$data['start']];
        }
        unset($data['dates']);
        $datas = [];
        foreach ($dates as $start) {
            $data['start'] = $start;
            $this->onBeforeAdd($data);
            $datas[] = $data;
        }
        Db::name($this->modelName)->insertAll($datas);
        $this->onAfterAdd($datas);
        $this->success(lang('route.add_success_info'));
    }

    protected function editPage(array $row)
    {
        $template = TourTemplate::getById($row['template_id']);
        $this->assign('template', $template);
        return parent::editPage($row);
    }

    protected function onBeforeDelete($id): array
    {
        $row = parent::onBeforeDelete($id);
        // TODO: 增加订单验证
        trace($row);
        return $row;
    }
}
